#!/bin/bash
# Bug reports and comments to Igor.Ermolaev@intel.com
hfnc=sha256sum
stmp=( stat -c '%Y %s' )
b64m=( '+/' '._' )
ch2b=`which xxd 2>/dev/null`

ccnt="$1"
idxs=( `echo "$2"|tr ',' ' '` )
shift 2

cidx=0
fidx=0
eqft=false
iidx=0
for argv in "$@"; do
   if [ $fidx -lt $cidx ]; then
      if [ $iidx -eq ${#idxs[@]} ]; then
         fidx=$(($#+1))
      else
         fidx=${idxs[$iidx]};((iidx++))
         if [ ${fidx:0:1} == '=' ]; then
            fidx=${fidx:1}
            eqft=true
         else
            eqft=false
         fi
      fi
   fi
   if [ $fidx -eq $cidx ]; then
      if [ $eqft == true ]; then
         modl=${argv#*=}
         argv=${argv%%=*}
      else
         modl="$argv"
         argv=''
      fi
      if [ $cidx -gt 0 ] || [ -x "$modl" ]; then
         modl="$(readlink -f "$modl")"
         mkey="$mkey"`"${stmp[@]}" "$modl"`" $(basename "$modl") "
         dkey=" $(dirname "$modl")$dkey"
         if [ $cidx -eq 0 ]; then
            ckey="$mkey"
            cend="$dkey"
            unset mkey dkey
         fi
      else
         ckey="$modl "
         cend=''
      fi
   fi
   if [ -n "$argv" ]; then
      if [ $cidx -le $ccnt ]; then
         ckey="$ckey$argv "
      else
         akey="$akey$argv "
      fi
   fi
   ((cidx++))
done
ckey="$ckey$ccnt$cend"
akey="$mkey$akey$(($#-1-ccnt))$dkey"

if [ -x "$ch2b" ];then
   chsh=`echo "$ckey"|$hfnc|awk '{print $1}'|"$ch2b" -r -p|base64 -w 0|tr "${b64m[@]}"`
   ahsh=`echo "$akey"|$hfnc|awk '{print $1}'|"$ch2b" -r -p|base64 -w 0|tr "${b64m[@]}"`
else
   chsh=`echo "$ckey"|$hfnc|awk '{print $1}'|sed 's/\(..\)/\1 /g'|awk '{for(i=1;i<=NF;i++){printf "%c", strtonum("0x"$i);}}'|base64 -w 0|tr "${b64m[@]}"`
   ahsh=`echo "$akey"|$hfnc|awk '{print $1}'|sed 's/\(..\)/\1 /g'|awk '{for(i=1;i<=NF;i++){printf "%c", strtonum("0x"$i);}}'|base64 -w 0|tr "${b64m[@]}"`
fi

if [ ! -w "$PWD" ] || [ -d "$PWD/.cached" ] && [ ! -w "$PWD/.cached" ]; then exec "$@"; fi

cdir="$PWD/.cached/$chsh/$ahsh"
mkdir -p "$cdir"

#cout=`grep -xFl -m 1 "$ckey $akey" "$cdir"/output.* 2>/dev/null`
cout=`find "$cdir" -name 'output.*' -print -exec head -n 1 {} \; 2>/dev/null|grep -xF -m 1 "$ckey $akey" -B 1|head -n 1`
if [ -z "$cout" ]; then
   ocnt=`ls -1 "$cdir"/output.* 2>/dev/null|wc -l`
   cout="$cdir"/output.$(printf '%03d' $ocnt)
   echo "$ckey $akey" >"$cout"
   "$@"|tee -a "$cout"
else
   tail -n +2 "$cout"
fi
